package com.hihusky.https;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hihusky.ScheduledTaskExecutorApplication;
import com.hihusky.Utils;
import com.hihusky.entity.Location;
import com.hihusky.entity.ReportRelatedIDs;
import com.hihusky.entity.User;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * the class will make multiple session to get IDs.
 */
public class ReportHandler {

    static Logger logger = LoggerFactory.getLogger(ScheduledTaskExecutorApplication.class);

    private User user;
    private ReportRelatedIDs reportRelatedIDs;
    private Location location;

    public ReportHandler() {
    }

    /**
     * init variables.
     * @param user include username and password to get token
     */
    public ReportHandler(User user, Location location) {
        this.user = user;
        this.reportRelatedIDs = new ReportRelatedIDs();
        this.location = location;
        requestForToken();
        requestForTaskIDAndTemplateIDByToken();
        requestDetailsIDByTokenAndTaskID();
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public ReportRelatedIDs getReportRelatedIDs() {
        return reportRelatedIDs;
    }

    public void setReportRelatedIDs(ReportRelatedIDs reportRelatedIDs) {
        this.reportRelatedIDs = reportRelatedIDs;
    }

    OkHttpClient client = Utils.okHttpClient;
    ObjectMapper objectMapper = Utils.objectMapper;

    /**
     * response body example:
     * {
     * "code": 0,
     * "msg": "登录成功",
     * "data": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6IntcInBlcm1pc3Npb25cIjpbXCJzdHVkZW50XCJdLFwic3lzVXNlclwiOntcImNvbGxlZ2VcIjpcIjNcIixcImNvbGxlZ2VPcmdJZFwiOlwiYzYyYWY5YWM4YzA1NGI0Mzg4ZTY3MjhmODQ3NjkwODNcIixcImNyZWF0ZVRpbWVcIjoxNjQxODg5MDc5MDAwLFwiY3JlYXRvclwiOlwiNjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2XCIsXCJlbmNvZGVVc2VyTmFtZVwiOlwiMGM4ZjYzMWE3NGNjZWU0MDYwMDVhYjBlZWEzYTUyNGJcIixcImdyYWRlT3JnSWRcIjpcIjJmNzQ3OGVkMWEwMDRkMzBiYTJlN2M2NzA2N2ZhNjg0XCIsXCJpZFwiOlwiYjAwNWMzOWI2OWM3NDQ5OTk0OWJhNTg2NTgyYTI0ZDdcIixcImlzTWFpblwiOlwiMVwiLFwibWFqb3JPcmdJZFwiOlwiNjJmOThmMmE3ZjliNDQ1NDgxYjI1YjE3NDdkY2JlY2VcIixcIm5hbWVcIjpcIuadjum4o1wiLFwicGFzc3dvcmRcIjpcIjkzMmI4ZDE1N2E4NjdiZjMyMGFmYjBjZWRiNzEyMmU5XCIsXCJwb3NpdGlvblwiOlwiM1wiLFwicmVtb3ZlVGFnXCI6XCIwXCIsXCJ1cGRhdGVUaW1lXCI6MTY0NjM2NTU1ODAwMCxcInVwZGF0ZXJcIjpcImRjNDQ2N2Q5NTFiNTQyNjg5MjVhNjhiYjE4NTI4YWU5XCIsXCJ1c2VyTmFtZVwiOlwiMjAxODAxMzk1NVwiLFwidXNlclVuaXF1ZVwiOlwiMGM4ZjYzMWE3NGNjZWU0MDYwMDVhYjBlZWEzYTUyNGJcIixcInZhbGlkU3RhdGVcIjpcIjFcIn0sXCJ1c2VySWRcIjpcImIwMDVjMzliNjljNzQ0OTk5NDliYTU4NjU4MmEyNGQ3XCJ9IiwiaXNzIjoiYXV0aDAiLCJleHAiOjE2NDcyMjg3NjIsImlhdCI6MTY0NjYyMzk2Mn0.lFbpe40kmUzHiYL839qy-KNSTf0LmmqqruFFr9HQpVo"
     * }
     */
    public void requestForToken() {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String bodyContent = String.format("userName=%s&password=%s", user.getUsername(), user.getPassword());
        RequestBody body = RequestBody.create(mediaType, bodyContent);
        Request request = new Request.Builder()
                .url("https://xgpt.wxc.edu.cn/sys/confirm/login.do")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Response response = client.newCall(request).execute();
            // Jackson setting
            JsonNode jsonNode = objectMapper.readTree(Objects.requireNonNull(response.body()).string());
            user.setToken(jsonNode.get("data").textValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * response body example:
     * {
     *     "code": 0,
     *     "msg": "操作成功！",
     *     "data": [
     *         {
     *             "removeTag": "0",
     *             "creator": "44a5706dc94544a991b1979957a57783",
     *             "createTime": "2022-03-07 08:53:21.0",
     *             "updater": "44a5706dc94544a991b1979957a57783",
     *             "updateTime": "2022-03-07 08:53:42.0",
     *             "id": "9f849dbe57834ca0964c0c65b955aa20",
     *             "templateName": "疫情日报（2022.3.7-13）",
     *             "templateId": "fc2265a19a9640109e6a9460d18257f6",
     *             "checkWay": "1",
     *             "frequency": "1",
     *             "dateUnit": "0",
     *             "number": "1",
     *             "beginTime": "2022-03-07",
     *             "endTime": "2022-03-13",
     *             "submitBeginTime": "00:00:00",
     *             "submitEndTime": "21:00:00",
     *             "yesOrNo": "0",
     *             "personType": "0",
     *             "isShow": "1",
     *             "releaseStatus": "1",
     *             "studentId": null,
     *             "percentage": null,
     *             "isTime": "0"
     *         }
     *     ],
     *     "pageNum": 1,
     *     "pageSize": 1,
     *     "pageTotal": 2
     * }
     */
    public void requestForTaskIDAndTemplateIDByToken() {

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "pageNum=1&pageSize=1");
        Request request = new Request.Builder()
                .url("https://xgpt.wxc.edu.cn/work/asd/epidemicDailyTask/findVoPageByToken.do")
                .method("POST", body)
                .addHeader("token", user.getToken())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Response response = client.newCall(request).execute();
            // Jackson
            JsonNode jsonNode = objectMapper.readTree(Objects.requireNonNull(response.body()).string());
            JsonNode dataNode = jsonNode.get("data");
            for (JsonNode objNode : dataNode) {
                String taskID = objNode.get("id").textValue();
                String templateID = objNode.get("templateId").textValue();
                reportRelatedIDs.setTaskID(taskID);
                reportRelatedIDs.setTemplateID(templateID);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * response body example:
     * {
     * "code": 0,
     * "msg": "操作成功！",
     * "data": [
     * {
     * "removeTag": null,
     * "creator": null,
     * "createTime": null,
     * "updater": null,
     * "updateTime": null,
     * "id": "af29b6327686451884f00f6ca1499b5c",
     * "taskId": null,
     * "beginTime": null,
     * "endTime": null,
     * "finishRatio": null,
     * "person": null,
     * "finishPerson": null,
     * "unfinishedPerson": null,
     * "planNum": null,
     * "realityNum": null,
     * "checkTime": "2022-03-07~2022-03-07",
     * "status": null,
     * "planNumVo": "1",
     * "realityNumVo": "1",
     * "major": null,
     * "grade": null,
     * "collegeName": null,
     * "collegeId": null,
     * "className": null,
     * "classId": null,
     * "counsellor": null,
     * "counsellorId": null,
     * "isDate": "1",
     * "isTime": "0",
     * "isShow": "1",
     * "isUpdate": "0"
     * }
     * ],
     * "pageNum": 1,
     * "pageSize": 10,
     * "pageTotal": 1
     * }
     */
    public void requestDetailsIDByTokenAndTaskID() {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "pageNum=1&pageSize=1");
        String url = String.format("https://xgpt.wxc.edu.cn/work/asd/epidemicDailyTaskDetails/findVoPageAndSubmitStatus.do?taskId=%s", reportRelatedIDs.getTaskID());
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("token", user.getToken())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Response response = client.newCall(request).execute();
            JsonNode jsonNode = objectMapper.readTree(Objects.requireNonNull(response.body()).string());
            JsonNode dataNode = jsonNode.get("data");
            for (JsonNode objNode : dataNode) {
                String detailsID = objNode.get("id").textValue();
                reportRelatedIDs.setDetailsID(detailsID);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * response body example:
     * {
     *     "code": 1,
     *     "msg": "已提交，请勿重复提交！",
     *     "data": null
     * }
     */
    public void requestForSubmitting() {

        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String formData = String.format(
                "0=否" +
                        "&2=36.5" +
                        "&3=否" +
                        "&4=是" +
                        "&5=" + simpleDateFormat.format(now) +
                        "&mx1=无星标" +
                        "&other3=" +
                        "&file=" +
                        "&address=" + location.getAddress() +
                        "&file=" +
                        "&object7=" + location.getAddress() +
                        "&id=" +
                        "&templateId=" + reportRelatedIDs.getTemplateID() +
                        "&taskId=" + reportRelatedIDs.getTaskID() +
                        "&detailsId=" + reportRelatedIDs.getDetailsID() +
                        "&isSave=1" +
                        "&province=" + location.getProvince() +
                        "&city=" + location.getCity() +
                        "&district=" + location.getDistrict() +
                        "&lng=" + location.getLongitude() +
                        "&lat=" + location.getLatitude() +
                        "&adCode=" + location.getAddressCode() +
                        "&answer=[{\"questionSort\":0,\"answer\":\"否\"},{\"questionSort\":1,\"answer\":\"[{\\\"checked\\\":true,\\\"id\\\":0,\\\"title\\\":\\\"绿色\\\"},{\\\"id\\\":1,\\\"title\\\":\\\"红色\\\"},{\\\"id\\\":2,\\\"title\\\":\\\"黄色\\\"},{\\\"id\\\":3,\\\"title\\\":\\\"有星标\\\"},{\\\"checked\\\":true,\\\"id\\\":4,\\\"title\\\":\\\"无星标\\\"}]\"},{\"questionSort\":2,\"answer\":\"36.5\"},{\"questionSort\":3,\"answer\":\"否\"},{\"questionSort\":4,\"answer\":\"是\"},{\"questionSort\":5,\"answer\":\"2022-04-03 06:10:01\"},{\"questionSort\":6,\"answer\":\"安徽省合肥市蜀山区高新技术产业开发区基金大厦\"},{\"questionSort\":7,\"answer\":\"安徽省合肥市蜀山区高新技术产业开发区基金大厦合肥创新产业园2期\"}]",
                simpleDateFormat.format(now),location.getAddress());
        RequestBody body = RequestBody.create(mediaType, formData);
        Request request = new Request.Builder()
                .url("https://xgpt.wxc.edu.cn/work/asd/templateSubmit/saveOrUpdate.do")
                .method("POST", body)
                .addHeader("token", user.getToken())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Response response = client.newCall(request).execute();
            JsonNode jsonNode = objectMapper.readTree(Objects.requireNonNull(response.body()).string());
            int code = jsonNode.get("code").asInt();
            String msg = jsonNode.get("msg").textValue();
            if (code == 0) {
                logger.info(msg);
            } else {
                logger.error(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
